package com.googlecode.recycled.lang.jse.api.concurrent;

import org.apache.commons.lang.UnhandledException;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

public class AsyncCaller {

    protected ExecutorService executor;

    public <T> AsyncResult<T> call(Callable<T> task) {
        final Future<T> f = executor.submit(task);
        return new AsyncResult<T>() {
            @Override
            public T get() {
                try {
                    return f.get();
                } catch (InterruptedException e) {
                    throw new UnhandledException(e);
                } catch (ExecutionException e) {
                    throw new UnhandledException(e);
                }
            }
        };
    }

    public void close() {
        executor.shutdown();
    }

    public void setExecutor(ExecutorService executor) {
        this.executor = executor;
    }

}
